package com.zhijs.struts.action;

import static java.lang.System.out;

import java.sql.Connection;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;

import com.h819.core.db.MyDbUtils;
import com.h819.core.web.jqgrid.JqgridListBaseAction;
import com.h819.core.web.jqgrid.Page;

/**
 * @Title: ShowModUpdateList.java
 * @Description: TODO(添加描述)
 * @author H819
 * @date 2010-4-19
 * @version V1.0
 */
public class ShowModUpdateListAction extends JqgridListBaseAction implements
		SessionAware {

	private Logger log = Logger.getLogger(ShowModUpdateListAction.class);
	private QueryRunner runner = new QueryRunner();;
	private Connection conn = null;
	Map session;

	Page p = this.getPage();

	public String execute() throws Exception {

		// 准备数据
		prepareDate();

		// 以下变量，必须赋值
		this.setCurPageNo(p.getPageNo());
		this.setTotalPages(p.getTotalPages());
		this.setTotalRecords(p.getTotalCount());
		this.setDataRows(this.getDataRows());

		log.info("当前页号：" + p.getPageNo());
		log.info("每页显示数据数量：" + p.getPageSize());
		log.info("数据总量：" + p.getTotalCount());
		log.info("排序变量：" + p.getOrderBy());
		log.info("升序/降序：" + p.getOrder());

		log.info("getDataRows size:" + this.getDataRows().size());

		for (Map m : this.getDataRows()) {
			StringUtils.center("getDataRows list ", 80, '*');
			for (Iterator it = m.entrySet().iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				System.out.println(entry.getKey() + " = " + entry.getValue());
			}
		}

		return SUCCESS;
	}

	private void prepareDate() {

		conn = MyDbUtils.getInstance("h819.properties").getOracleConnection235();

		try {
			// 计算记录数目
			String queryCount = "select count(1) from zhijs_standard_view zjsv,st_modify stm,st_standard sts where zjsv.st_standardcode = stm.standard_code and zjsv.st_standardcode = sts.standard_code and not exists(select xgd.standard_code from zhijs_xgd xgd where xgd.standard_code = zjsv.st_standardcode)";

			log.info("queryCount : " + queryCount);

			// 计算记录总数
			Map<String, Object> r7 = runner.query(conn, queryCount,
					new MapHandler());

			for (Iterator it = r7.entrySet().iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				totalRecords = Integer.parseInt(entry.getValue().toString());
				// out.println(entry.getKey() + " = " + entry.getValue());
			}

			// 给 page 设置必要参数
			p.setTotalCount(totalRecords);

			// 计算分页
			int begin = p.getFirst();
			int end = begin + p.getPageSize() - 1;
			if (end >= this.getTotalRecords())
				end = Long.valueOf(this.getTotalRecords()).intValue();

			// 起始位置
			String limitFrom = String.valueOf(begin);
			// 结束位置
			String limitTo = String.valueOf(end);

			log.info("in zhijs : limitFrom = " + limitFrom);
			log.info("in zhijs : limitTo = " + limitTo);

			// 查询所有的有更新的标准
			String queryModList = "select temptable.*  from (select row_number() over(order by zjsv.st_type) as num ,zjsv.st_standardcode,sts.namecn,sts.text_address,zjsv.zhijs_departmentcode,zjsv.zhijs_department,stm.modify_number,stm.file_address from zhijs_standard_view zjsv,st_modify stm,st_standard sts where zjsv.st_standardcode = stm.standard_code and zjsv.st_standardcode = sts.standard_code and not exists(select xgd.standard_code from zhijs_xgd xgd where xgd.standard_code = zjsv.st_standardcode) )"
					+ "temptable where num between "
					+ limitFrom
					+ " AND "
					+ limitTo
					+ " order by zhijs_department,st_standardcode,modify_number";

			log.info("queryModList = " + queryModList);

			// 重新构造返回值，每次都重新初始化
			List<Map<String, Object>> newSearchData = new ArrayList<Map<String, Object>>();
			// MultiValueMap 用于存放文本信息,和其他方法中用的一致，便于统一处理
			ArrayList<MultiValueMap> textAddressList = new ArrayList<MultiValueMap>();

			List<Map<String, Object>> listModify;
			listModify = runner.query(conn, queryModList, new MapListHandler());

			// 记录序号，和 NUM 不同，此 id 用来记录记录集的排序号，可以区分选择了哪条记录.下载文件的时候用的此变量
			int id = 0;
			if (listModify != null)
				for (Map m : listModify) {// 查询所有的有更新的标准,每次循环是一条标准题录
					out.println(StringUtils.center("标准更新题录信息", 80, '*'));
					id++;
					// 临时变量，重新组合数据用重新构造返回值
					Map<String, Object> tempMap = new TreeMap<String, Object>();

					// 存放找到的文本地址信息
					MultiValueMap dataRowsTempMap = new MultiValueMap();

					// TreeMap<String, Object> temptm = new TreeMap<String,
					// Object>();

					for (Iterator it = m.entrySet().iterator(); it.hasNext();) { // 每条标准的具体信息
						Map.Entry entry = (Map.Entry) it.next();
						System.out.println(entry.getKey() + " = "
								+ entry.getValue());

						String value = "";
						if (entry.getValue() != null)
							value = entry.getValue().toString();

						// 修改页面传递的信息
						if (entry.getKey().toString().equals("TEXT_ADDRESS")) {// 

							tempMap.put(entry.getKey().toString(), "浏览");
							dataRowsTempMap.put(entry.getKey().toString(),
									value);

						} else if (entry.getKey().toString().equals(
								"FILE_ADDRESS")) {

							tempMap.put(entry.getKey().toString(), "浏览");
							dataRowsTempMap.put(entry.getKey().toString(),
									value);

						}

						else {
							// 其他字段不做处理
							tempMap.put(entry.getKey().toString(), value);
							dataRowsTempMap.put(entry.getKey().toString(),
									value);

						}

					}// 单条记录处理完成

					tempMap.put("ACTION", "更新");
					// 记录行号，便于以后定位该条记录
					dataRowsTempMap
							.put("id", Integer.valueOf(id).toString());
					newSearchData.add(tempMap);
					textAddressList.add(dataRowsTempMap);

				}// 所有的记录信息

			// 为页面赋值
			this.setDataRows(newSearchData);
			// 放入 session ，下载文件时,再次检索
			session.put("resultdata", textAddressList);

		} catch (SQLException e) {
			DbUtils.printStackTrace(e);

		} finally {
			DbUtils.closeQuietly(conn);
		}
	}

	/*
	 * 以下getter方法必须实现，struts2-json插件会将这些getter方法序列化，以便输出json对象。
	 * 这些getter方法只需返回相应的属性即可。如getCurPage应该返回curPage （curPage在JsonBaseAction中有定义）
	 */
	@Override
	public int getCurPageNo() {
		return this.curPageNo;
	}

	@Override
	public List<Map<String, Object>> getDataRows() {
		return this.dataRows;
	}

	@Override
	public long getTotalPages() {
		return this.totalPages;
	}

	@Override
	public long getTotalRecords() {
		return this.totalRecords;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.struts2.interceptor.SessionAware#setSession(java.util.Map)
	 */
	public void setSession(Map session) {
		this.session = session;
	}

}
